<?php

namespace App\Http\Repository;

use App\Admin;

class AdminRepository
{
    private $admin;
    private $id;
    private $result;

    public function __construct(Admin $admin)
    {
        $this->result = true;
        $this->admin = $admin;
    }

    //通过id删除管理员
    public function delAdminById($id)
    {
        $this->id = $id;
        //删除管理员
        \DB::transaction(function () {
            $this->result = \App\AdminGaterLine::where('admin', $this->id)->delete();
            $this->result = \App\Admin::where('id', $this->id)->delete();
        });

        return $this->result;
    }

    //通过id得到管理员信息
    public function getAdminById($id)
    {
        $admin = \App\Admin::select('admins.id', 'admins.name', 'admins.email', 'admins.status', \DB::raw('group_concat(admin_gater_lines.gater) as gater'))
            ->join('admin_gater_lines', 'admin_gater_lines.admin', '=', 'admins.id')
            ->groupBy('admins.id')
            ->findorfail($id);
        $admin->gater = explode(',', $admin->gater);
        return $admin;
    }

    //管理员重新分类权限
    public function reGater($id, $gaters, $clear)
    {
        $this->id = $id;
        $this->gaters = $gaters;
        $this->clear = $clear;
        \DB::transaction(function () {
            $this->clear && \App\AdminGaterLine::where('admin', $this->id)->delete();

            foreach ($this->gaters as $gater) {
                \App\AdminGaterLine::create(['admin' => $this->id, 'gater' => $gater]);
            }
        });
    }

    //得到管理员id | name 的list
    public function getAdminsByLists()
    {
        return $this->admin
            ->lists('name', 'id');
    }
}